import os
import importlib
from flask import Flask, abort, request

app = Flask(__name__)

# 规划蓝图模块都位于'bp'目录下
blueprints_dir = 'bp'

def register_blueprints(app, blueprints_dir):
    # 遍历blueprints目录下的所有子目录
    for filename in os.listdir(blueprints_dir):
        path = os.path.join(blueprints_dir, filename)
        if os.path.isdir(path) and '__init__.py' in os.listdir(path):
            # 构建蓝图模块的名称
            module_name = f'{blueprints_dir}.{filename}'
            # 动态导入蓝图模块
            module = importlib.import_module(module_name)
            # 假设每个蓝图模块都有一个名为'blueprint'的变量
            blueprint = getattr(module, 'blueprint', None)
            if blueprint:
                # 注册蓝图到Flask应用
                app.register_blueprint(blueprint, url_prefix=f'/{filename}')

# 在应用创建后调用函数注册所有蓝图
register_blueprints(app, blueprints_dir)

@app.before_request
def before_request():
    if request.path.startswith('/blog'):
        token = request.headers.get('Authorization')
        if not token:
            abort(401)

if __name__ == '__main__':
    app.run(debug=True)